<template>
  <div class="history-view">
    <el-row :gutter="16" class="main-row">
      <!-- 中间内容区域 -->
      <el-col :xs="24" :sm="14" :md="16" class="content-col">
        <div class="main-content">
          <div class="header-section">
            <div class="title-section">
              <h2>历史记录</h2>
              <el-tag type="info" v-if="!searchKeyword">共 {{ historyList.length }} 条记录</el-tag>
              <el-tag type="success" v-else>找到 {{ filteredHistoryList.length }} 条匹配记录</el-tag>
            </div>

            
            <div class="filter-section">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索历史记录..."
                class="search-input"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>

              <el-select
                v-model="sortBy"
                placeholder="排序方式"
                class="sort-select"
              >
                <el-option label="最新提问" value="newest" />
                <el-option label="最早提问" value="oldest" />
                <el-option label="难度升序" value="difficultyAsc" />
                <el-option label="难度降序" value="difficultyDesc" />
              </el-select>

              <el-select
                v-model="filterType"
                placeholder="筛选"
                class="filter-select"
              >
                <el-option label="全部" value="all" />
                <el-option label="已学会" value="learned" />
                <el-option label="已收藏" value="collected" />
              </el-select>
            </div>
          </div>

          <el-empty v-if="!filteredHistoryList.length" description="暂无历史记录" />
          
          <div v-else class="history-list" ref="historyListRef">
            <div 
              v-for="(item, index) in filteredHistoryList" 
              :key="item.id"
              :id="`question-${item.id}`"
              class="history-item"
              :class="{ 'slide-in': true }"
              :style="{ animationDelay: `${index * 0.1}s` }"
            >
              <div class="history-header">
                <div class="history-meta">
                  <div class="history-left">
                    <div class="difficulty-rating">
                      <span class="difficulty-label">难度</span>
                      <el-rate
                        v-model="item.difficulty"
                        :colors="difficultyColors"
                        :max="5"
                        @change="updateDifficulty(item)"
                      />
                    </div>
                  </div>
                  <div class="history-right">
                    <div class="history-actions">
                      <el-button
                        :type="Boolean(item.isLearned) ? 'success' : 'default'"
                        size="small"
                        class="learn-button"
                        @click="toggleLearned(item)"
                      >
                        <el-icon class="button-icon">
                          <Check v-if="Boolean(item.isLearned)"/>
                          <Edit v-else/>
                        </el-icon>
                        {{ Boolean(item.isLearned) ? "已学会" : "学习中" }}
                      </el-button>
                      <div 
                        class="collect-button"
                        :class="{ 'is-collected': Boolean(item.isCollected) }"
                        @click="toggleCollect(item)"
                      >
                        <el-icon class="star-icon">
                          <Star />
                        </el-icon>
                      </div>
                    </div>
                    <div class="history-buttons">
                      <el-button
                        type="danger"
                        size="small"
                        @click="deleteHistory(item.id)"
                      >
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                      <el-button
                        type="primary"
                        size="small"
                        @click="regenerateAnswer(item)"
                      >
                        <el-icon><Refresh /></el-icon>
                        重新生成
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="history-content">
                <div class="question">
                  <el-icon><ChatRound /></el-icon>
                  <div class="question-content">
                    <div class="question-text">{{ item.question }}</div>
                    <el-tooltip 
                      :content="formatDetailedTime(item.createTime)"
                      placement="top"
                    >
                      <span class="question-create-time">
                        <el-icon><Clock /></el-icon>
                        {{ formatTime(item.createTime) }}
                      </span>
                    </el-tooltip>
                  </div>
                </div>
                <div class="answer-content" :class="{ expanded: item.answer }">
                  <div class="markdown-content" 
                       v-html="formatAnswer(item.answer)"
                       :class="{ visible: item.answer }"
                  ></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 右侧布局 -->
      <el-col :xs="24" :sm="10" :md="8" class="right-col">
        <div class="sidebar">
          <!-- 主题卡片 -->
          <el-card class="topics-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">热门主题</span>
              </div>
            </template>

            <div class="topics-cloud">
              <el-tag
                v-for="topic in topTopics"
                :key="topic.name"
                class="topic-tag"
                @click="searchByTopic(topic.name)"
              >
                {{ topic.name }} <span class="topic-count">({{ topic.count }})</span>
              </el-tag>
            </div>
          </el-card>

          <!-- 目录卡片 -->
          <el-card class="catalog-card">
            <template #header>
              <div class="card-header">
                <div class="header-left">
                  <span class="card-title">问题目录</span>
                  <span class="catalog-count" v-if="searchKeyword">
                    ({{ filteredHistoryList.length }}/{{ historyList.length }})
                  </span>
                </div>
                <el-button
                  type="text"
                  @click="isCatalogCollapsed = !isCatalogCollapsed"
                >
                  <el-icon>
                    <component :is="isCatalogCollapsed ? 'ArrowRight' : 'ArrowDown'" />
                  </el-icon>
                </el-button>
              </div>
            </template>

            <div class="catalog-container-wrapper">
              <el-scrollbar class="catalog-scrollbar">
                <div class="catalog-list">
                  <div
                    v-for="item in (searchKeyword ? filteredHistoryList : historyList)"
                    :key="item.id"
                    :class="['catalog-item', { 'active': activeQuestionId === item.id }]"
                    :data-id="item.id"
                    @click="scrollToQuestion(item.id)"
                  >
                    <div class="catalog-content">
                      <div class="catalog-title">{{ item.question }}</div>
                      <div class="catalog-meta">
                        <span class="catalog-time">
                          <el-icon><Clock /></el-icon>
                          {{ formatTime(item.createTime) }}
                        </span>
                        <div class="catalog-tags">
                          <el-tag size="small" :type="Boolean(item.isLearned) ? 'success' : 'info'" class="mini-tag">
                            {{ Boolean(item.isLearned) ? "已学会" : "学习中" }}
                          </el-tag>
                          <el-tag size="small" :type="Boolean(item.isCollected) ? 'warning' : 'info'" class="mini-tag">
                            {{ Boolean(item.isCollected) ? "已收藏" : "收藏" }}
                          </el-tag>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, shallowRef, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Clock, ChatRound, Star, Check, Edit, Delete, Refresh, ArrowRight, ArrowDown } from '@element-plus/icons-vue'
import axios from 'axios'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { debounce } from 'lodash-es'
import { formatRelativeTime, formatDetailTime } from '@/utils/timeFormat'
import { useRoute } from 'vue-router'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
import QuestionContent from '@/components/QuestionContent.vue'

const historyList = ref([])
const editor = shallowRef()
const searchKeyword = ref('')
const sortBy = ref('newest')
const filterType = ref('all')
const activeQuestionId = ref(null)
const isCatalogCollapsed = ref(false)
const contentMaxHeight = ref('0px')
const catalogMaxHeight = ref('calc(100vh - 60px - 16px - 16px - 40px)') // 初始最大高度，减去顶部导航栏、上下padding和底部40px距离
const isExpanding = ref(false)
const catalogInitialHeight = 400 // 初始高度值

const route = useRoute()

const historyListRef = ref(null)
const catalogContainerRef = ref(null)

// 添加响应式的目录高度计算
const catalogHeight = ref('330px')

// 计算统计数据
const learnedCount = computed(() => 
  historyList.value.filter(q => q.isLearned).length
)

const collectedCount = computed(() => 
  historyList.value.filter(q => q.isCollected).length
)

// 计算学习进度
const learningProgress = computed(() => {
  if (!historyList.value.length) return 0
  return Math.round((learnedCount.value / historyList.value.length) * 100)
})

const progressStatus = computed(() => {
  if (learningProgress.value >= 80) return 'success'
  if (learningProgress.value >= 50) return 'warning'
  return ''
})

const percentageFormat = (percentage) => `学习进度 ${percentage}%`

// 过滤和排序后的列表
const filteredHistoryList = computed(() => {
  let filtered = [...historyList.value]
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(item => 
      item.question.toLowerCase().includes(keyword) ||
      item.answer.toLowerCase().includes(keyword) ||
      (item.keywords || '').toLowerCase().includes(keyword)
    )
  }
  
  // 类型筛选
  if (filterType.value === 'learned') {
    filtered = filtered.filter(item => item.isLearned)
  } else if (filterType.value === 'collected') {
    filtered = filtered.filter(item => item.isCollected)
  }
  
  // 排序
  if (sortBy.value === 'oldest') {
    filtered.sort((a, b) => new Date(a.createTime) - new Date(b.createTime))
  } else if (sortBy.value === 'difficultyAsc') {
    filtered.sort((a, b) => a.difficulty - b.difficulty)
  } else if (sortBy.value === 'difficultyDesc') {
    filtered.sort((a, b) => b.difficulty - a.difficulty)
  } else {
    filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  }
  
  return filtered
})

// 热门主题
const topTopics = computed(() => {
  const topics = {}
  historyList.value.forEach(item => {
    const keywords = item.keywords?.split(',') || []
    keywords.forEach(keyword => {
      if (keyword.trim()) {
        topics[keyword.trim()] = (topics[keyword.trim()] || 0) + 1
      }
    })
  })
  
  return Object.entries(topics)
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => b.count - a.count)
    .slice(0, 20) // 增加显示数量到20个
})

// 最近活动
const recentActivities = computed(() => {
  return historyList.value.slice(0, 5).map(item => ({
    content: item.question,
    timestamp: item.timestamp,
    type: item.isLearned ? 'success' : 'info'
  }))
})

// 编辑器配置
const editorConfig = {
  readOnly: true,
  autoFocus: false,
  scroll: false,
  maxLength: 99999,
  placeholder: '',
  MENU_CONF: {
    codeBlock: {
      languageList: [
        { text: 'Java', value: 'java' },
        { text: 'JavaScript', value: 'javascript' },
        { text: 'HTML', value: 'html' },
        { text: 'CSS', value: 'css' },
        { text: 'Python', value: 'python' },
        { text: 'SQL', value: 'sql' },
        { text: 'Bash', value: 'bash' },
        { text: 'Plain Text', value: 'plaintext' }
      ]
    }
  },
  hoverbarKeys: {
    text: []
  }
}

const handleCreated = (e) => {
  editor.value = e
}

const formatAnswer = (answer) => {
  if (!answer) {
    contentMaxHeight.value = '0px'
    return ''
  }
  
  // 处理代码块，直接返回原始内容让wangEditor处理
  let formattedContent = answer.replace(/```(\w*)([\s\S]*?)```/g, (match, language, code) => {
    language = language.trim() || 'plaintext'
    code = code.trim()
    return `<pre><code class="language-${language}">${code}</code></pre>`
  })

  // 处理行内代码，直接返回原始内容让wangEditor处理
  formattedContent = formattedContent.replace(/`([^`]+)`/g, (match, code) => {
    return `<code>${code}</code>`
  })

  // 处理标题
  formattedContent = formattedContent
    .replace(/^##### (.*$)/gm, '<h5>$1</h5>')
    .replace(/^#### (.*$)/gm, '<h4>$1</h4>')
    .replace(/^### (.*$)/gm, '<h3>$1</h3>')
    .replace(/^## (.*$)/gm, '<h2>$1</h2>')
    .replace(/^# (.*$)/gm, '<h1>$1</h1>')

  // 处理水平线
  formattedContent = formattedContent.replace(/^---$/gm, '<hr>')

  // 处理列表
  let inList = false
  formattedContent = formattedContent.split('\n').map(line => {
    const listMatch = line.match(/^- (.+)$/)
    if (listMatch) {
      if (!inList) {
        inList = true
        return `<ul><li>${listMatch[1]}</li>`
      }
      return `<li>${listMatch[1]}</li>`
    } else if (inList && line.trim()) {
      inList = false
      return `</ul>${line}`
    } else if (inList && !line.trim()) {
      inList = false
      return '</ul>'
    }
    return line
  }).join('\n')

  // 处理其他 Markdown 语法
  formattedContent = formattedContent
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>')

  // 处理普通文本段落
  return formattedContent.split('\n').map(line => {
    if (line.trim() && 
        !line.includes('<h') && 
        !line.includes('<pre>') && 
        !line.includes('</pre>') &&
        !line.includes('<hr>') && 
        !line.includes('<ul>') && 
        !line.includes('<li>') && 
        !line.includes('</ul>') &&
        !line.includes('</div>')) {
      return `<p>${line}</p>`
    }
    return line
  }).join('\n')

  // 在内容格式化完成后，设置合适的最大高度
  nextTick(() => {
    const answerElements = document.querySelectorAll('.answer-content')
    answerElements.forEach(el => {
      const scrollHeight = el.scrollHeight
      el.style.maxHeight = scrollHeight + 'px'
    })
  })

  return formattedContent
}

const formatTime = (timestamp) => {
  return formatRelativeTime(timestamp)
}

const formatDetailedTime = (timestamp) => {
  return formatDetailTime(timestamp)
}

const handleSearch = debounce(() => {
  // 重置排序和筛选
  if (!searchKeyword.value) {
    sortBy.value = 'newest'
    filterType.value = 'all'
  }
}, 300)

const searchByTopic = (topic) => {
  searchKeyword.value = topic
}

const randomTagType = () => {
  const types = ['info', 'success', 'warning', 'danger']
  return types[Math.floor(Math.random() * types.length)]
}

const fetchHistory = async () => {
  try {
    const response = await axios.get('/api/questions')
    // 确保每个item的属性都是响应式的，并正确处理布尔值
    historyList.value = response.data.map(item => ({
      ...item,
      isCollected: item.isCollected === true || item.isCollected === 'true' || item.collected === true || item.collected === 'true',
      isLearned: item.isLearned === true || item.isLearned === 'true' || item.learned === true || item.learned === 'true',
      difficulty: Number(item.difficulty || 0)
    }))
    
    // 调试输出
    console.log('处理后的数据:', historyList.value.map(item => ({
      id: item.id,
      isCollected: item.isCollected,
      isLearned: item.isLearned,
      originalCollected: item.collected,
      originalLearned: item.learned
    })))
  } catch (error) {
    ElMessage.error('获取历史记录失败')
  }
}

const deleteHistory = async (id) => {
  try {
    await axios.delete(`/api/questions/${id}`)
    await fetchHistory()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const toggleLearned = async (item) => {
  try {
    // 立即更新前端状态
    item.isLearned = !item.isLearned
    
    await axios.post(`/api/questions/${item.id}/learned`, {
      isLearned: item.isLearned
    })
    
    ElMessage.success(item.isLearned ? '已标记为已学习' : '已取消学习标记')
  } catch (error) {
    // 如果请求失败,恢复原状态
    item.isLearned = !item.isLearned
    ElMessage.error('操作失败')
  }
}

const toggleCollect = async (item) => {
  try {
    // 立即更新前端状态
    item.isCollected = !item.isCollected
    
    await axios.post(`/api/questions/${item.id}/collect`, {
      isCollected: item.isCollected
    })
    
    ElMessage.success(item.isCollected ? '已收藏' : '已取消收藏')
  } catch (error) {
    // 如果请求失败,恢复原状态
    item.isCollected = !item.isCollected
    ElMessage.error('操作失败')
  }
}

const regenerateAnswer = async (item) => {
  try {
    await axios.post(`/api/questions/${item.id}/regenerate`)
    await fetchHistory()
    ElMessage.success('答案已重新生成')
  } catch (error) {
    ElMessage.error('重新生成失败')
  }
}

const difficultyColors = ['#67C23A', '#E6A23C', '#F56C6C']

const updateDifficulty = async (item) => {
  try {
    await axios.post(`/api/questions/${item.id}/difficulty?difficulty=${item.difficulty}`)
    ElMessage.success('难度评分已更新')
  } catch (error) {
    ElMessage.error('更新难度评分失败')
  }
}

// 修改 scrollToQuestion 函数
const scrollToQuestion = (id) => {
  const element = document.getElementById(`question-${id}`)
  if (element) {
    // 滚动到目标问题的顶部
    element.scrollIntoView({ 
      behavior: 'smooth',
      block: 'start'  // 改为 'start' 使其从顶部开始显示
    })
    
    activeQuestionId.value = id
    
    // 高亮显示一段时间后消失
    setTimeout(() => {
      element.classList.add('highlight')
      setTimeout(() => {
        element.classList.remove('highlight')
      }, 2000)
    }, 500)
  }
}

// 完全重写目录滚动处理函数
const handleCatalogScroll = (e) => {
  // 使用 el-scrollbar 后，不再需要手动处理滚动
  // 但保留此函数以便将来可能的扩展
}

// 修改 updateContentHeight 函数
const updateContentHeight = () => {
  nextTick(() => {
    const answerElements = document.querySelectorAll('.answer-content')
    answerElements.forEach(el => {
      const actualHeight = el.querySelector('.markdown-content').scrollHeight
      el.style.setProperty('--content-height', `${actualHeight + 48}px`) // 48px 是内边距
    })
  })
}

// 简化重置函数 - 不再需要设置目录高度
const resetCatalogHeight = () => {
  // 使用固定高度，不再需要动态计算
}

// 添加回 updateActiveQuestion 函数
const updateActiveQuestion = debounce(() => {
  if (!historyListRef.value) return
  
  const questions = historyListRef.value.querySelectorAll('.history-item')
  const scrollTop = historyListRef.value.scrollTop
  
  // 找到当前滚动位置最接近顶部的问题
  let activeQuestion = null
  let minDistance = Infinity

  questions.forEach((question) => {
    // 获取元素相对于滚动容器的位置
    const distance = Math.abs(question.offsetTop - scrollTop)
    if (distance < minDistance) {
      minDistance = distance
      activeQuestion = question
    }
  })

  if (activeQuestion) {
    const id = parseInt(activeQuestion.id.replace('question-', ''))
    if (activeQuestionId.value !== id) {
      activeQuestionId.value = id
      
      // 更新目录项的选中状态
      document.querySelectorAll('.catalog-item').forEach(item => {
        if (item.dataset.id === String(id)) {
          item.classList.add('active')
        } else {
          item.classList.remove('active')
        }
      })
    }
  }
}, 100)

// 在组件挂载时初始化
onMounted(async () => {
  await fetchHistory()
  
  // 监听主内容区域的滚动
  const historyList = historyListRef.value
  if (historyList) {
    historyList.addEventListener('scroll', updateActiveQuestion)
    // 初始化时触发一次更新
    updateActiveQuestion()
  }

  // 如果有 scrollTo 参数,滚动到指定问题
  const scrollToId = route.query.scrollTo
  if (scrollToId) {
    setTimeout(() => {
      scrollToQuestion(parseInt(scrollToId))
    }, 500)
  }

  // 初始化代码高亮
  updateHighlight()

  // 在组件挂载时也执行一次
  updateContentHeight()

  // 初始化目录高度
  resetCatalogHeight()

  // 计算目录高度
  calculateCatalogHeight()
})

// 修改 onUnmounted 钩子
onUnmounted(() => {
  const historyList = historyListRef.value
  if (historyList) {
    historyList.removeEventListener('scroll', updateActiveQuestion)
  }
})

// 在内容更新后应用代码高亮
const updateHighlight = () => {
  nextTick(() => {
    document.querySelectorAll('.markdown-content pre code').forEach((block) => {
      hljs.highlightElement(block)
    })
  })
}

// 监听列表变化，更新高亮
watch(() => historyList.value, updateHighlight, { deep: true })

// 监听搜索关键词变化，重置目录高度
watch(searchKeyword, () => {
  resetCatalogHeight()
})

// 监听筛选条件变化，重置目录高度
watch([sortBy, filterType], () => {
  resetCatalogHeight()
})

// 计算目录高度的函数
const calculateCatalogHeight = () => {
  // 获取视窗高度
  const viewportHeight = window.innerHeight
  // 计算其他元素占用的高度（头部导航60px + 上下padding 32px + 卡片头部等固定元素约80px）
  const otherElementsHeight = 172
  // 设置最小高度
  const minHeight = 330
  // 计算可用高度
  const availableHeight = viewportHeight - otherElementsHeight
  // 使用可用高度和最小高度中的较大值
  const height = Math.max(availableHeight, minHeight)
  
  catalogHeight.value = `${height}px`
}

// 监听窗口大小变化
onMounted(() => {
  calculateCatalogHeight() // 初始计算
  window.addEventListener('resize', calculateCatalogHeight)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', calculateCatalogHeight)
})
</script>

<style scoped>
.history-view {
  min-height: calc(100vh - 60px);
  position: relative;
  padding: 0;
}

.main-row {
  min-height: calc(100vh - 60px);
  margin: 0 !important;
  position: relative;
}

/* 中间内容区域 */
.content-col {
  padding: 24px;
  background: white;
  min-height: calc(100vh - 60px);
}

.main-content {
  margin: 0 auto;
}

/* 右侧布局 */
.right-col {
  position: fixed;
  top: 60px;
  right: 0;
  height: calc(100vh - 60px);
  overflow: hidden;
  padding-bottom: 40px; /* 添加底部padding */
  box-sizing: border-box; /* 确保padding计入高度 */
}

.sidebar {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow: hidden;
}

/* 主题卡片 */
.topics-card {
  flex: 0 0 auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #E2E8F0;
  margin-top: 10px;
}

.topics-cloud {
  padding: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.topic-tag {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 500;
  background: #F8FAFC;
  border: 1px solid #E2E8F0;
}

/* 标签颜色变化 */
.topic-tag:nth-child(6n+1) {
  color: #3B82F6;
  border-color: #BFDBFE;
  background-color: #F0F7FF;
}

.topic-tag:nth-child(6n+2) {
  color: #10B981;
  border-color: #A7F3D0;
  background-color: #ECFDF5;
}

.topic-tag:nth-child(6n+3) {
  color: #F59E0B;
  border-color: #FDE68A;
  background-color: #FFFBEB;
}

.topic-tag:nth-child(6n+4) {
  color: #8B5CF6;
  border-color: #DDD6FE;
  background-color: #F5F3FF;
}

.topic-tag:nth-child(6n+5) {
  color: #EC4899;
  border-color: #FBCFE8;
  background-color: #FDF2F8;
}

.topic-tag:nth-child(6n) {
  color: #06B6D4;
  border-color: #A5F3FC;
  background-color: #ECFEFF;
}

/* 悬停效果 */
.topic-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.topic-tag:nth-child(6n+1):hover {
  background-color: #DBEAFE;
}

.topic-tag:nth-child(6n+2):hover {
  background-color: #D1FAE5;
}

.topic-tag:nth-child(6n+3):hover {
  background-color: #FEF3C7;
}

.topic-tag:nth-child(6n+4):hover {
  background-color: #EDE9FE;
}

.topic-tag:nth-child(6n+5):hover {
  background-color: #FCE7F3;
}

.topic-tag:nth-child(6n):hover {
  background-color: #CFFAFE;
}

/* 点击效果 */
.topic-tag:active {
  transform: translateY(0);
}

/* 计数样式 */
.topic-count {
  display: inline-block;
  margin-left: 4px;
  font-size: 12px;
  opacity: 0.7;
}

/* 目录卡片 */
.catalog-card {
  flex: 1;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #E2E8F0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 调整最大高度计算，考虑底部padding */
  max-height: calc(100vh - 60px - 32px - 200px - 40px);
  margin-bottom: 0; /* 移除margin-bottom */
}

.catalog-container-wrapper {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 330px;
}

.catalog-scrollbar {
  flex: 1;
  border-radius: 8px;
  height: 100%;
}

.catalog-scrollbar :deep(.el-scrollbar__wrap) {
  height: 85%;
}

.catalog-card :deep(.el-card__body) {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.catalog-list {
  padding: 4px;
  padding-bottom: 8px; /* 减小底部padding */
}

.catalog-item {
  padding: 10px;
  margin: 8px;  /* 稍微减小边距 */
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  background: white;
  border: 1px solid #E2E8F0;
}

.catalog-item:hover {
  background: #F0F7FF;
  border-color: #3B82F6;
  transform: translateY(-2px);
}

.catalog-item.active {
  background: #F0F7FF;
  border-color: #3B82F6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.catalog-title {
  font-size: 13px;
  color: #1E293B;
  line-height: 1.5;
  font-weight: 500;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.catalog-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 4px;
}

.catalog-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #64748B;
  font-size: 12px;
}

.catalog-tags {
  display: flex;
  gap: 4px;
}

.mini-tag {
  height: 18px;
  line-height: 16px;
  padding: 0 6px;
  font-size: 11px;
  border-radius: 4px;
}

/* 卡片头部样式 */
.card-header {
  padding: 8px 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #F8FAFC;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-left span {
  font-size: 14px;
  font-weight: 600;
  color: #64748B;
}

.catalog-count {
  font-size: 11px;
  font-weight: 500;
  background: none;
  padding: 0;
}

/* 折叠按钮样式 */
.catalog-card :deep(.el-button--text) {
  padding: 2px;
  height: 20px;
  width: 20px;
  min-height: 20px;
  color: #94A3B8;
  display: flex;
  align-items: center;
  justify-content: center;
}

.catalog-card :deep(.el-button--text:hover) {
  color: #3B82F6;
  background: #F0F7FF;
  border-radius: 4px;
}

.catalog-card :deep(.el-button--text .el-icon) {
  font-size: 14px;
}

/* 历史记录列表样式 */
.history-item {
  padding: 24px;
  margin-bottom: 24px;
  border-radius: 16px;
  background: #F8FAFC;
  border: 1px solid #E2E8F0;
  transition: all 0.2s ease;
}

.history-item:hover {
  border-color: #3B82F6;
  background: #F0F7FF;
}

.history-header {
  margin-bottom: 20px;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.history-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.history-time {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748B;
  font-size: 14px;
}

.difficulty-rating {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid #E2E8F0;
}

.difficulty-label {
  color: #64748B;
  font-size: 14px;
  font-weight: 500;
}

.history-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.history-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.learn-button {
  height: 36px;
  padding: 0 16px;
  font-weight: 500;
  border-radius: 8px;
  font-size: 14px;
}

.collect-button {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: white;
  border: 1px solid #E2E8F0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.collect-button:hover {
  border-color: #F59E0B;
  background: #FEF3C7;
  color: #F59E0B;
}

.collect-button.is-collected {
  background: #FEF3C7;
  border-color: #F59E0B;
  color: #F59E0B;
}

.question {
  padding: 24px;
  background: white;
  border-radius: 12px;
  border: 1px solid #E2E8F0;
  margin-bottom: 12px;
}

.question-content {
  flex: 1;
}

.question-text {
  font-size: 16px;
  color: #1E293B;
  margin-bottom: 12px;
  line-height: 1.6;
  font-weight: 600;
}

.question-create-time {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #64748B;
  font-size: 14px;
}

.answer-content {
  padding: 24px;
  background: white;
  border-radius: 12px;
  border: 1px solid #E2E8F0;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.5s ease-in-out;
}

.answer-content.expanded {
  max-height: var(--content-height, 1000px);
}

.markdown-content {
  font-size: 15px;
  line-height: 1.8;
  color: #334155;
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.3s ease-out;
}

.markdown-content.visible {
  opacity: 1;
  transform: translateY(0);
}

.markdown-content :deep(pre) {
  background: #F8FAFC;
  border-radius: 12px;
  padding: 20px;
  margin: 24px 0;
  border: 1px solid #E2E8F0;
}

.markdown-content :deep(code) {
  font-family: 'JetBrains Mono', ui-monospace, monospace;
  font-size: 14px;
}

/* 搜索和筛选区域 */
.filter-section {
  display: flex;
  gap: 16px;
  margin: 24px 0;
  justify-content: flex-end;
  flex-wrap: wrap;
  background: #F8FAFC;
  padding: 16px;
  border-radius: 12px;
  border: 1px solid #E2E8F0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 280px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  background: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding: 0 12px;
  height: 40px;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__inner) {
  height: 40px;
  font-size: 14px;
  color: #1E293B;
}

.search-input :deep(.el-input__wrapper:hover),
.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #3B82F6;
}

.search-input :deep(.el-input__prefix) {
  color: #64748B;
}

.sort-select,
.filter-select {
  width: 140px;
}

.sort-select :deep(.el-input__wrapper),
.filter-select :deep(.el-input__wrapper) {
  border-radius: 8px;
  background: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding: 0 12px;
  height: 40px;
  transition: all 0.3s ease;
}

.sort-select :deep(.el-input__inner),
.filter-select :deep(.el-input__inner) {
  height: 40px;
  font-size: 14px;
  color: #1E293B;
}

.sort-select :deep(.el-input__wrapper:hover),
.filter-select :deep(.el-input__wrapper:hover),
.sort-select :deep(.el-input__wrapper.is-focus),
.filter-select :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #3B82F6;
}

.sort-select :deep(.el-select__caret),
.filter-select :deep(.el-select__caret) {
  color: #64748B;
  font-size: 14px;
}

/* 标题区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 16px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 0;
}

.title-section h2 {
  font-size: 28px;
  font-weight: 700;
  color: #1E293B;
  margin: 0;
  line-height: 1.4;
  position: relative;
}

.title-section h2::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 40px;
  height: 3px;
  background: #3B82F6;
  border-radius: 2px;
}

.title-section .el-tag {
  font-size: 14px;
  font-weight: 500;
  padding: 6px 14px;
  border-radius: 8px;
  height: auto;
  background: #F0F7FF;
  border-color: #3B82F6;
  color: #3B82F6;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #CBD5E1;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #F1F5F9;
  border-radius: 3px;
}

/* 响应式调整 */
@media screen and (max-width: 1280px) {
  .content-col {
    margin-right: 320px;
  }
  
  .right-col {
    width: 320px;
  }
}

@media screen and (max-width: 768px) {
  .content-col {
    margin-right: 0;
    padding: 16px;
  }
  
  .right-col {
    display: none;
  }
  
  .filter-section {
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
  }
  
  .sort-select,
  .filter-select {
    width: calc(50% - 8px);
  }
}

/* 高亮动画效果 */
@keyframes highlight-pulse {
  0% {
    background: #F0F7FF;
    border-color: #3B82F6;
  }
  50% {
    background: #DBEAFE;
    border-color: #2563EB;
  }
  100% {
    background: #F0F7FF;
    border-color: #3B82F6;
  }
}

.history-item.highlight {
  animation: highlight-pulse 2s ease;
}

/* 目录项目激活状态 */
.catalog-item.active {
  background: #F0F7FF;
  border-color: #3B82F6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

/* 确保目录容器可以滚动 */
.catalog-container {
  overflow-y: auto;
  scroll-behavior: smooth;
}

/* 主内容区域滚动行为 */
.history-list {
  scroll-behavior: smooth;
}

/* 移除渐变遮罩效果，因为它可能会遮挡底部内容 */
.catalog-fade {
  display: none;
}

/* 响应式调整 */
@media screen and (max-height: 768px) {
  .catalog-card {
    max-height: calc(100vh - 60px - 32px - 150px - 40px);
  }
}

@media screen and (max-height: 600px) {
  .catalog-container-wrapper {
    min-height: 250px;
  }
  
  .catalog-item {
    margin: 6px;  /* 在小屏幕上进一步减小边距 */
    padding: 8px;
  }
}
</style> 